<?php

namespace App\Http\Controllers\School;

use App\Http\Requests\School\StoreSchoolRule;
use App\Http\Resources\School\SchoolRuleResource;
use App\Models\SchoolAdminLog;
use App\Models\SchoolRule;

/**
 * Class SchoolRuleController
 * @package App\Http\Controllers\School
 * 学校规则
 */
class SchoolRuleController extends BaseController
{
    /**
     * @param StoreSchoolRule $request
     * @param SchoolRule $schoolRule
     * @return SchoolRuleResource|array
     * 修改学校规则
     */
    public function update(StoreSchoolRule $request, SchoolRule $schoolRule)
    {
        // 筛选早中晚三餐时间有重叠的情况
        if ($request->morning_date[1] <= $request->lunch_date[0] && $request->lunch_date[1] <= $request->dinner_date[0]) {
            $schoolRule->fill($request->all());
            $schoolRule->morning_start = $request->morning_date[0];
            $schoolRule->morning_end = $request->morning_date[1];
            $schoolRule->lunch_start = $request->lunch_date[0];
            $schoolRule->lunch_end = $request->lunch_date[1];
            $schoolRule->dinner_start = $request->dinner_date[0];
            $schoolRule->dinner_end = $request->dinner_date[1];
            $schoolRule->is_limit = $request->is_limit;
            $schoolRule->save();
            SchoolAdminLog::Log('修改学校规则');
            return new SchoolRuleResource($schoolRule);
        } else {
            return $this->fail('早中晚三餐时间不能有重叠');
        }
    }

    /**
     * @return SchoolRuleResource
     * 显示学校规则
     */
    public function index()
    {
        $schoolRule = SchoolRule::where('school_id', \Auth::user()->school_id)->first();
        return new SchoolRuleResource($schoolRule);
    }
}
